layui.config({
	base : "js/"
}).use(['form','layer','jquery','laypage','upload'],function(){
	var form = layui.form(),
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		laypage = layui.laypage,
		$ = layui.jquery;

	//加载页面数据
	var usersData = '';
	var orgId = window.sessionStorage.getItem("organizeId");

	$.get($.httpRootPath()+"/api/web/member/i/"+orgId+"/org", function(data){
		usersData = JSON.parse(data).data;
		//执行加载数据的方法
		usersList();
	})

	//查询
	$(".search_btn").click(function(){
		var userArray = [];
		if($(".search_input").val() != ''){
			var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
            setTimeout(function(){
            	$.ajax({
					url : $.httpRootPath()+"/api/web/member/i/"+orgId+"/org",
					type : "get",
					dataType : "json",
					success : function(data){
						if(window.sessionStorage.getItem("addUser")){
							var addUser = window.sessionStorage.getItem("addUser");
							usersData = JSON.parse(addUser).concat(data);
						}else{
							usersData = data;
						}
						for(var i=0;i<usersData.length;i++){
							var usersStr = usersData[i];
							var selectStr = $(".search_input").val();
		            		function changeStr(data){
		            			var dataStr = '';
		            			var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
		            			if(showNum > 1){
									for (var j=0;j<showNum;j++) {
		            					dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
		            				}
		            				dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
		            				return dataStr;
		            			}else{
		            				dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
		            				return dataStr;
		            			}
		            		}
		            		//用户名
		            		if(usersStr.userName.indexOf(selectStr) > -1){
			            		usersStr["userName"] = changeStr(usersStr.userName);
		            		}
		            		//用户邮箱
		            		if(usersStr.userEmail.indexOf(selectStr) > -1){
			            		usersStr["userEmail"] = changeStr(usersStr.userEmail);
		            		}
		            		//性别
		            		if(usersStr.userSex.indexOf(selectStr) > -1){
			            		usersStr["userSex"] = changeStr(usersStr.userSex);
		            		}
		            		//会员等级
		            		if(usersStr.userGrade.indexOf(selectStr) > -1){
			            		usersStr["userGrade"] = changeStr(usersStr.userGrade);
		            		}
		            		if(usersStr.userName.indexOf(selectStr)>-1 || usersStr.userEmail.indexOf(selectStr)>-1 || usersStr.userSex.indexOf(selectStr)>-1 || usersStr.userGrade.indexOf(selectStr)>-1){
		            			userArray.push(usersStr);
		            		}
		            	}
		            	usersData = userArray;
		            	usersList(usersData);
					}
				})
            	
                layer.close(index);
            },2000);
		}else{
			layer.msg("请输入需要查询的内容");
		}
	})

	//添加会员
	$(".infoAdd_btn").click(function(){
		var index = layui.layer.open({
			title : "添加会员",
			type : 2,
			area: ['500px', '300px'],
			content : "add.html",
			success : function(layero, index){
				setTimeout(function(){
					layui.layer.tips('点击此处返回会员列表', '.layui-layer-setwin .layui-layer-close', {
						tips: 3
					});
				},500)
			}
		})
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
		$(window).resize(function(){
			layui.layer.full(index);
		})
//		layui.layer.full(index);
	})
	$(".mem-pre-mould-down").click(function(){
		if(orgId == ""){
			return;
		}
		var str = $.httpRootPath()+"/api/web/load/i/"+ orgId + "/down/org";
		window.location.href = str;
	})
	$(".mem-export").click(function(){
		if(orgId == ""){
			return;
		}
		var str = $.httpRootPath()+"/api/web/load/i/"+ orgId + "/export/mem";
		window.location.href = str;
	})
	$(".mem-import").click(function(){
		var index = layui.layer.open({
			title : "导入信息",
			type : 2,
			content : "loadin.html",
			success : function(layero, index){
				setTimeout(function(){
					layui.layer.tips('点击此处返回会员列表', '.layui-layer-setwin .layui-layer-close', {
						tips: 3
					});
				},500)
			}
		})
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
		$(window).resize(function(){
			layui.layer.full(index);
		})
		layui.layer.full(index);
	})
	//批量删除
	$(".batchDel").click(function(){
		var $checkbox = $('.users_list tbody input[type="checkbox"][name="checked"]');
		var $checked = $('.users_list tbody input[type="checkbox"][name="checked"]:checked');
		if($checkbox.is(":checked")){
			layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
				var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
	            setTimeout(function(){
	            	//删除数据
	            	for(var j=0;j<$checked.length;j++){
	            		for(var i=0;i<usersData.length;i++){
							if(usersData[i].newsId == $checked.eq(j).parents("tr").find(".news_del").attr("data-id")){
								usersData.splice(i,1);
								usersList(usersData);
							}
						}
	            	}
	            	$('.users_list thead input[type="checkbox"]').prop("checked",false);
	            	form.render();
	                layer.close(index);
					layer.msg("删除成功");
	            },2000);
	        })
		}else{
			layer.msg("请选择需要删除的成员");
		}
	})

    //全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断文章是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})

	//操作
	$("body").on("click",".info_edit",function(){  //编辑
		var orgId = window.sessionStorage.getItem("organizeId");
		var _this = $(this);
		var data = {orgId:orgId}
		var edit = getOrganize(data);
		var memberNum = _this.attr("data-id");
		console.log("memberNum"+memberNum);
		window.sessionStorage["memberNumEditId"] = memberNum;
		var html ='';
		if(edit){
			var index = layui.layer.open({
				title: "编辑信息",
				type: 2,
				content: "edit.html",
				success: function(layero, index) {
					setTimeout(function() {
						layui.layer.tips('点击此处返回成员列表', '.layui-layer-setwin .layui-layer-close', {
							tips: 3
						});
					}, 500)
				}
			})
		}else{
			var index = layui.layer.open({
				title: "编辑信息",
				type: 2,
				content: "editOrg.html",
				area: ['500px', '300px'],
				success: function(layero, index) {
					setTimeout(function() {
						layui.layer.tips('点击此处返回成员列表', '.layui-layer-setwin .layui-layer-close', {
							tips: 3
						});
					}, 500)
				}
			})
		}
			//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
			$(window).resize(function() {
				layui.layer.full(index);
			})
			layui.layer.full(index);
	})
	
	//操作
	$("body").on("click",".users_info",function(){  //编辑
		
		var _this = $(this);
		var memberNum = _this.attr("data-id");
		window.sessionStorage["memberNumEditId"] = memberNum;
			var index = layui.layer.open({
				title: "编辑信息",
				type: 2,
				content: "info.html",
				success: function(layero, index) {
					setTimeout(function() {
						layui.layer.tips('点击此处返回成员列表', '.layui-layer-setwin .layui-layer-close', {
							tips: 3
						});
					}, 500)
				}
			})
			//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
			$(window).resize(function() {
				layui.layer.full(index);
			})
			layui.layer.full(index);
	})

	$("body").on("click",".info_del",function(){  //删除
		var _this = $(this);
		layer.confirm('确定删除此用户？',{icon:3, title:'提示信息'},function(index){
			_this.parents("tr").remove();
			var memberNum =_this.attr("data-id");
			var data = {
				memberNum:memberNum,
				orgId:orgId
			}
			deleteInfo(data,function(){
				layer.close(index);
			});
			
		});
	})


	function usersList(){
		//渲染数据
		function renderDate(data,curr){
			
			var dataHtml = '';
			currData = usersData.concat().splice(curr*nums-nums, nums);
			if(currData.length != 0){
				for(var i=0;i<currData.length;i++){
					var cdi = currData[i];
					var memState = "";
					console.log("memstate");
					if(cdi.memberNum_mem == ''){
						memState = "未注册";
					}else if (cdi.name == ''){
						memState = '注册未完善'
					}else if(cdi.entryType =='1' && cdi.confirm != '1'){
						memState = "预录入未确认";
					}else if (cdi.orgAuth == '1'){
						memState ='未授权';
					}else{
						memState = '正常';
					}
					memState = '<a class="layui-btn layui-btn-mini">'+memState+'</a>'
					
					dataHtml += '<tr>'
			    	+  '<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
			    	+  '<td>'+cdi.memberNum+'</td>'
			    	+  '<td>'+cdi.name+'</td>'
			    	+  '<td>'+cdi.depName+'</td>'
			    	+  '<td>'+cdi.proName+'</td>'
			    	+  '<td>'+memState+'</td>'
			    	+  '<td>'
					+    '<a class="layui-btn layui-btn-mini info_edit" data-id="'+cdi.memberNum+'"><i class="iconfont icon-edit"></i> 编辑</a>'
					+    '<a class="layui-btn layui-btn-danger layui-btn-mini info_del" data-id="'+cdi.memberNum+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
					+    '<a class="layui-btn layui-btn-mini layui-btn-mini users_info" data-id="'+cdi.memberNum+'"><i class="layui-icon">&#xe606;</i>详情</a>'
			        +  '</td>'
			    	+'</tr>';
				}
			}else{
				dataHtml = '<tr><td colspan="8">暂无数据</td></tr>';
			}
		    return dataHtml;
		}

		//分页
		var nums = 10; //每页出现的数据量
		laypage({
			cont : "page",
			pages : Math.ceil(usersData.length/nums),
			jump : function(obj){
				$(".users_content").html(renderDate(usersData,obj.curr));
				$('.users_list thead input[type="checkbox"]').prop("checked",false);
		    	form.render();
			}
		})
	}
        
})
function deleteInfo(data,callback) {
    $.ajax({
        url: $.httpRootPath()+'/api/web/organize/i/'+data.orgId+"/del-mem",
        type: 'POST',
        dataType: 'json',
        data: data,
        timeout: 15000,
        cache: false,
        success: function (r) {
            if (r.code == "00") {
              	layer.msg("删除成功！");
            } else {
               layer.msg(r.msg);
            }
        },
        error: function (e) {
          layer.msg("系统错误！");
        },
        complete:function(){
        	callback();
        }
    });
   }
function getOrganize(data) {
	var edit = false;
    $.ajax({
        url: $.httpRootPath()+"/api/web/organize/i/"+data.orgId,
        type: 'GET',
        dataType: 'json',
        data: data,
        timeout: 15000,
        cache: false,
        async:false,
        success: function (r) {
            if (r.code == '00' && r.data.type =='2') {
             edit = true;
            } 
        },
        error: function (e) {
          layer.msg("系统错误！");
        }
    });
    return edit;
   }